package controllers

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type Controller struct{}

func (this Controller) SessionGet(key string, c *gin.Context) interface{} {
	session := sessions.Default(c)
	return session.Get(key)
}
func (this Controller) GetDefaultStr(key, value string, c *gin.Context) string {
	v := c.PostForm(key)
	if v == "" {
		return value
	}
	return v
}
func (this Controller) GetDefaultInt(key string, value int, c *gin.Context) int {
	v := c.PostForm(key)
	s, err := strconv.Atoi(v)
	if err != nil {
		return value
	}
	return s
}

func (this Controller) SessionSet(key string, value interface{}, c *gin.Context) error {
	session := sessions.Default(c)
	session.Set(key, value)
	err := session.Save()
	if err != nil {
		return err
	}
	return nil
}

func (this Controller) SessionDelete(key string, c *gin.Context) error {
	session := sessions.Default(c)
	value := session.Get(key)
	if value != nil {
		session.Delete(key)
		err := session.Save()
		if err != nil {
			return err
		}
	}
	return nil
}

func (Controller) SessionIdGet(c *gin.Context) (sessionId string, err error) {
	sessionId, err = c.Cookie("sessionId")
	return
}

func (this Controller) ReturnJson(code int, msg string, data interface{}, c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  msg,
		"data": data,
	})
}
